package com.wika.basics.widget

import android.content.Context
import android.graphics.BlurMaskFilter
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.wika.basics.R
import com.wika.basics.utils.ViewUtils


/**
 *@Description: 自定义发光圆形控件
 *@Date: 2024/7/25 9:54
 *@Author: WangWeiShuo
 */
class LightView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
): View(context, attrs, defStyleAttr) {
    private var lightPaint: Paint? = null
    private var centerX = 0
    private var centerY = 0
    private var radius = 20

    init {
        lightPaint = Paint()
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        initAttribute(context,attrs)

    }

    private fun initAttribute(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.LightView)
        if(typedArray != null){
            val style = typedArray.getInt(R.styleable.LightView_style, 2)
            val normalColor = typedArray.getColor(R.styleable.LightView_normalColor, ContextCompat.getColor(context,R.color.gray_27000000))
            val pressedColor = typedArray.getColor(R.styleable.LightView_pressedColor, ContextCompat.getColor(context,R.color.gray_27000000))
            val luminousRange = typedArray.getDimensionPixelSize(R.styleable.LightView_light_range, ViewUtils.dp2px(context,10f)).toFloat()
            lightPaint?.color = normalColor
//            ViewUtils.setViewSelector(context,this,normalColor,pressedColor)
            setBlurType(style,luminousRange)
            typedArray.recycle()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        centerX = left + measuredWidth / 2
        centerY = top + measuredHeight / 2
        radius = measuredWidth / 3
        super.onMeasure(widthMeasureSpec, widthMeasureSpec)
    }

    /**
     * 设置发光位置和范围
     * @param blurType Int 类型
     * @param range Float 发光范围
     */
    private fun setBlurType(blurType: Int,range:Float) {
        when (blurType) {
            0 -> lightPaint?.maskFilter =
                BlurMaskFilter(range, BlurMaskFilter.Blur.INNER)

            1 -> lightPaint?.maskFilter =
                BlurMaskFilter(range, BlurMaskFilter.Blur.NORMAL)

            2 -> lightPaint?.maskFilter =
                BlurMaskFilter(range, BlurMaskFilter.Blur.SOLID)

            3 -> lightPaint?.maskFilter =
                BlurMaskFilter(range, BlurMaskFilter.Blur.OUTER)
        }
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawCircle(centerX.toFloat(), centerY.toFloat(), radius.toFloat(), lightPaint!!)
    }
}